package com.humngyang.com.hmy.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TreeUtile {

    public static List<Map<String, Object>> parseTree(List<Map<String, Object>> list) {
        List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
        Map<String, Object> tmpMap = new HashMap<String, Object>();
        for (int i = 0, l = list.size(); i < l; i++) {
            tmpMap.put(String.valueOf(list.get(i).get("id")), list.get(i));
        }
        for (int i = 0, l = list.size(); i < l; i++) {
            Map<String, Object> map = list.get(i);
            //tmpMap存储的均为id为key的键值对，如果以pid为key可以取出对象，则表明该元素是父级元素
            if (tmpMap.get(map.get("pid")) != null && (map.get("id") != map.get("pid"))) {
                //给当前这个父级map对象中添加key为children的ArrayList
                if ((tmpMap.get(map.get("pid")) != null) && ((Map<String, Object>) tmpMap.get(map.get("pid"))).get("children") == null) {
                    ((Map<String, Object>) tmpMap.get(map.get("pid"))).put("children", new ArrayList<Map<String, Object>>());
                }
                Map<String, Object> tmap = (Map<String, Object>) tmpMap.get(map.get("pid"));
                ArrayList<Map<String, Object>> tArrayList = (ArrayList<Map<String, Object>>) tmap.get("children");
                tArrayList.add(list.get(i));            //没有父节点
            } else {
                resultList.add(list.get(i));
            }
        }
        return resultList;
    }

}
